<template>
  <!-- 关联答案 -->
  <div>
    <!-- 基本信息 -->
    <div class="policy-main circulationInfo">
      <div class="base-mian-cell-title mt clearfix">
        <div class="left fl">
          <i></i>
          <span class="tips">基本信息</span>
        </div>
      </div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="150px"
        style="overflow: hidden; padding: 20px 85px 0 30px"
      >
        <el-col :span="8" class="common-box">
          <el-form-item label="规则包编码：">
            <el-input v-model="form.rulePkgCode" placeholder="系统自动生成" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="common-box">
          <el-form-item label="规则包名称：" prop="rulePkgName">
            <el-input v-model="form.rulePkgName" placeholder="请输入" :disabled="type == 'view'" :maxlength="20"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="common-box" v-if="type == 'view'">
          <el-form-item label="发布日期：">
            <el-date-picker
              disabled
              value-format="yyyy-MM-dd"
              v-model="form.publishTime"
              type="date">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8" class="common-box" v-else>
          <el-form-item label="发布类型：" prop="publishType">
            <el-radio-group v-model="form.publishType">
              <el-radio label="1">全量发布</el-radio>
              <el-radio label="2">增量发布</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col :span="24" class="common-box">
          <el-form-item label="备注：">
            <el-input
              :disabled="type == 'view'"
              type="textarea"
              :rows="3"
              v-model="form.remark"
              placeholder="请输入备注"
              :maxlength="400"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-form>
    </div>

    <!-- 答案信息 -->
    <div class="policy-main circulationInfo">
      <div class="base-mian-cell-title mt clearfix">
        <div class="left fl">
          <i></i>
          <span class="tips">规则包信息</span>
        </div>
      </div>

      <!-- 具体配置 -->
      <div class="content">
        <!-- 左侧树 -->
        <div class="left-tree">
          <div class="tree-filter">
            <el-input
              placeholder="查找规则文件"
              v-model="filterText"
              suffix-icon="el-icon-search"
            >
            </el-input>
          </div>
          <el-tree
            :data="treeData"
            show-checkbox
            :filter-node-method="filterNode"
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps"
            @check-change="checkChange"
          >
          </el-tree>
        </div>

        <!-- 右侧具体包列表 -->
        <div class="right-main">
          <el-table
            v-loading="loading"
            :data="tableData"
            highlight-current-row
            header-cell-class-name="table-header-class"
            style="width: 100%"
            height="450"
          >
            <el-table-column
              label="序号"
              type="index"
              align="center"
              width="70"
            >
            </el-table-column>
            <el-table-column
              min-width="120"
              property="diseaseName"
              label="疾病名称"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              min-width="120"
              property="diseaseRuleType"
              label="规则组名称"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span>{{diseaseRuleDic.filter(fItem=>fItem.value == scope.row.diseaseRuleType)[0].label }}</span>
              </template>
            </el-table-column>

            <el-table-column
              min-width="120"
              property="ruleGroupVersionName"
              label="版本名称"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              min-width="120"
              property="updateId"
              label="最后修改人"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              min-width="120"
              property="updateTime"
              label="修改日期"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              label="操作"
              align="center"
              width="130"
              fixed="right"
            >
              <template slot-scope="scope">
                <div style="display: flex; justify-content: center">
                  <span
                    class="handle-btn"
                    @click="colView(scope.$index, scope.row)"
                    >查看</span
                  >
                  <span
                    v-if="type!='view'"
                    class="handle-btn"
                    @click="colDelete(scope.$index, scope.row)"
                    >删除</span
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!-- 保存按钮 -->
    <el-row style="padding: 20px; background: #fff">
      <el-col :span="24" class="text_center">
        <el-button type="danger" class="Defaultbutton" @click="saveInfo" v-if="type!='view'">保存</el-button>
        <el-button type="danger" @click="goBack">返回</el-button>
      </el-col>
    </el-row>

    <!-- 查看规则配置弹窗 -->
    <el-dialog
      v-if="ruleVisible"
      title="规则配置详情"
      :visible.sync="ruleVisible"
      top="10vh"
      width="1200px"
      :show-close="true"
      :close-on-click-modal="false"
      center>
      <!-- 体检风险规则组件 -->
      <physicalRiskRule v-if="currentType == '1'" ref="physicalRiskRule" :projectCategoryDic="projectCategoryDic" :projectNameDic="projectNameDic" :logicDic="logicDic" :pageDisabled="true"></physicalRiskRule>
      <!-- 健康风险规则组件 -->
      <healthRiskRule v-else-if="currentType == '2'" ref="healthRiskRule" :logicDic="logicDic" :pageDisabled="true"></healthRiskRule>
      <!-- 特殊评分项规则组件 -->
      <specialScoreRule v-else-if="currentType == '3'" ref="specialScoreRule" :logicDic="logicDic" :pageDisabled="true"></specialScoreRule>
      <!-- 核保结论规则组件 -->
      <underwriteEvaluationRule v-else-if="currentType == '4'" ref="underwriteEvaluationRule" :logicDic="logicDic" :pageDisabled="true"></underwriteEvaluationRule>
    </el-dialog>
  </div>
</template>

<script>
// 处理树结构
const treeDataHandle = (array, _this, childrenName = "children") => {
  if (!Array.isArray(array)) return [];
  let level = 0;
  let sort = 0;
  const recursive = (array, level) => {
    level++;
    return array.map((v) => {
      v._level = level;
      if (v._level == 3) {
        sort++;
        v._sort = sort;
        _this.sortObj[v.id + ''] = sort;
      }

      // 处理label
      if(v._level == 1) v.label = v.diseaseName
      if(v._level == 2){
        v.label = _this.diseaseRuleDic.filter(item=>item.value == v.ruleType)[0].label
      }
      if(v._level == 3) v.label = v.versionName

      // 处理children
      // 体检类型层
      if(!v[childrenName] && v.itemVoList) {
        v.itemVoList.forEach(vItem=>{
          vItem.diseaseName = v.diseaseName
        })
        v[childrenName] = v.itemVoList
      }
      // 版本层
      if(!v[childrenName] && v.versionList) {
        v.versionList.forEach(vItem=>{
          vItem.diseaseId = v.diseaseList
          vItem.diseaseName = v.diseaseName
          vItem.diseaseRuleType = v.ruleType
        })
        v[childrenName] = v.versionList
      }

      // 处理id
      if(v._level == 1) v.id = v.id + 'level1'
      if(v._level == 2) v.id = v.id + 'level2'
      if(v._level == 3) v.id = v.id + ''

      if(_this.type == 'view') v._disabled = true

      const child = v[childrenName];
      if (child && child.length) recursive(child, level);
      return v;
    });
  };
  return recursive(array, level);
};

import physicalRiskRule from "../../../component/physicalRiskRule";
import healthRiskRule from "../../../component/healthRiskRule";
import specialScoreRule from "../../../component/specialScoreRule";
import underwriteEvaluationRule from "../../../component/underwriteEvaluationRule";

import constant from "@/utils/constant";
import { getRulePackageDetailApi,getRulePublishMenuApi,insertRulePublishApi,saveRulePublishApi,getNameDictProjectApi,getProjectCategoryApi,getProjectNameApi,getOwnDictProjectApi } from "@/api/medicalLibrary/examProjectLibrary";

export default {
  components: {
		physicalRiskRule,
    healthRiskRule,
    specialScoreRule,
    underwriteEvaluationRule,
	},
  data() {
    return {
      diseaseRuleDic: [],
      projectCategoryDic: [],  //体检项对象.项目大类
      projectNameDic: [], //体检项对象.项目名称
      logicDic: [], //逻辑符
      form: {
        rulePkgCode: '',
        rulePkgName: '',
        // publishType: '1',
        remark: '',
      },
      rules: {
        rulePkgCode: [
          { required: true, message: "请输入规则包编号", trigger: "blur" },
        ],
        rulePkgName: [
          { required: true, message: "请输入规则包名称", trigger: "blur" },
        ],
        publishType: [
          { required: true, message: "请选择发布类型", trigger: "change" },
        ],
      },

      // 来源
      type: "add",

      // 规则包信息
      filterText: "",
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
        disabled: (data, node) => {
          if(data._disabled) return true
          if (node.level == 1 || node.level == 2) return true;
          let checkId = node.parent.childNodes.filter((item) => item.checked);
          if (checkId.length) {
            if (!node.checked) return true;
            else return false;
          }
          return false;
        },
      },

      // 版本号对应的优先级
      sortObj: {},
      // 列表
      tableData: [],
      loading: false,

      // 弹窗
      ruleVisible: false,
      currentType: ''
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getNameDictProject()
    this.getPhysicalDic()

  },
  activated (){
    this.form = {
      rulePkgCode: '',
      rulePkgName: '',
      // publishType: '1',
      remark: '',
    }
    this.tableData = []
    setTimeout(()=>{
      this.$refs.form.clearValidate()
    },0)
    this.type = this.$route.query.type;
    if(this.$route.name == 'rulePackageView' || this.$route.name == 'rulePackageEdit') this.getRulePackDetail();
    else this.getRulePublishMenu()
  },
  mounted() {
  },
  methods: {
    // 过滤节点
    filterNode(value, data, node) {
      let parentNode = node.parent // 父级node
      let labels = [node.label] // 当前node的名字
      let level = 1 // 层级
      while (level < node.level) {
        labels = [...labels, parentNode.label] // 当前node名字，父级node的名字
        parentNode = parentNode.parent
        level++
      }
      return labels.some(d => d.indexOf(value) !== -1)
    },
    // 查询逻辑符
    getNameDictProject(){
      getOwnDictProjectApi({code: 'ruleType'}).then(res => {
				if (res.resultCode == constant.SUCCESS) {
					this.diseaseRuleDic = res.data || []
          this.diseaseRuleDic.forEach(item=>{
            item.value = item.remark
            item.label = item.dictValue
          })
				}
			})
      getNameDictProjectApi({name: '逻辑符'}).then(res => {
				if (res.resultCode == constant.SUCCESS) {
					this.logicDic = res.data
				}
			})
    },
    // 查询体检项对象.项目大类、项目名称、测量结果的列表数据
    getPhysicalDic(){
      // 项目大类
      getProjectCategoryApi({}).then(res => {
				if (res.resultCode == constant.SUCCESS) {
					this.projectCategoryDic = res.data
				}
			})
      // 项目名称
      getProjectNameApi({}).then(res => {
				if (res.resultCode == constant.SUCCESS) {
					this.projectNameDic = res.data
				}
			})
    },
    // 新增查询左侧菜单
    getRulePublishMenu(){
      getRulePublishMenuApi().then((res) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          this.treeData = res.data
          treeDataHandle(this.treeData, this);
        }
      }).catch((err) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
      });
    },
    // 查看和编辑获取详细数据
    getRulePackDetail() {
      getRulePackageDetailApi({ id: this.$route.query.id })
      .then((res) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode == constant.SUCCESS) {
          // 基本信息
          this.form = res.data && res.data.publishLsit ? res.data.publishLsit[0] : {}
          
          // 选中的版本信息
          this.tableData = res.data.pkgInfoList || [];

          // 树形组件数据
          this.treeData = res.data.packageList
          treeDataHandle(this.treeData, this);

          // 通过列表的id设置树形选中
          setTimeout(()=>{
            this.$refs.tree.setCheckedKeys(this.tableData.map(item => item.ruleGroupVersionId));
            this.tableDataHandle();
          },0)
        }
      })
      .catch((err) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
      });
    },
    // 处理列表数据，给列表添加排序_sort
    tableDataHandle() {
      this.tableData.forEach(item => {
        item._sort = this.sortObj[item.ruleGroupVersionId];
      });
    },
    // 节点选中状态发生变化时的回调
    checkChange(data, checkFlag) {
      if(data._level != 3) return
      // 节点选中，判断列表是否已经存在改节点信息
      if (checkFlag) {
        let filterArr = this.tableData.filter(item => item.ruleGroupVersionId == data.id);
        if (filterArr.length) return;
        else {
          let rowData = {
            diseaseId: data.diseaseId,
            diseaseRuleId: data.diseaseRuleId,
            ruleGroupVersionId: data.id,
            diseaseName: data.diseaseName,
            diseaseRuleType: data.diseaseRuleType,
            ruleGroupVersionName: data.versionName,
            version: data.version,
            updateId: data.updateId,
            updateTime: data.updateTime,
            status: data.status,
            _sort: data._sort
          }
          if (!this.tableData.length) this.tableData.push(rowData);
          else {
            let _index = 0;
            try {
              this.tableData.forEach((item, index) => {
                if (data._sort < item._sort) {
                  _index = index;
                  throw new Error("");
                }
              });
            } catch (error) {
              this.tableData.splice(_index, 0, rowData);
              return;
            }
            this.tableData.push(rowData);
          }
        }
      } else {
        // 节点取消选中，删除列表对应的数据
        let ids = this.tableData.map((item) => item.ruleGroupVersionId);
        if (ids.indexOf(data.id) > -1)
          this.tableData.splice(ids.indexOf(data.id), 1);
      }
    },

    // 列表点击删除时触发
    colDelete(index, row) {
      this.tableData.splice(index, 1);
      this.$refs.tree.setCheckedKeys(this.tableData.map(item => item.ruleGroupVersionId))
    },

    // 列表点击查看按钮时触发
    colView(index,row){
      this.currentType = row.diseaseRuleType
      this.ruleVisible = true
      let refName = row.diseaseRuleType == '1' ? 'physicalRiskRule' : row.diseaseRuleType == '2' ? 'healthRiskRule' : row.diseaseRuleType == '3' ? 'specialScoreRule' : 'underwriteEvaluationRule'
      setTimeout(()=>{
        this.$refs[refName].getRiskRule(row.diseaseRuleId,row.version)
      },0)
    },

    // 点击保存时触发
    saveInfo(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(this.form,'form');
          let params = {
            ...this.form,
            rulePkgInfoList: this.tableData
          }
          let url = this.type == 'add' ? insertRulePublishApi : saveRulePublishApi
          let msg = this.type == 'add' ? '规则新增成功' : '规则修改成功'
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          url(params).then((res) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
            if (res.resultCode == constant.SUCCESS) {
              this.$message.success(msg)
              this.goBack()
            }
          }).catch((err) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
          });
        }
      });
    },
    // 点击页面返回按钮
    goBack() {
      this.$router.push({
        path: "/home/maintenance/robouUnderwriting/intelligenceRule/rulePublishing",
      });
    },
  },
};
</script>

<style lang = "less" scoped>
.policy-main {
  background: #fff;
  .base-mian-cell-title {
    margin: 0px 20px;
    padding: 0 20px;
    height: 48px;
    line-height: 48px;
    border-bottom: 1px solid #e1e1e1;
    overflow: hidden;
    .left {
      .line {
        color: #f76767;
        float: left;
      }
      .tips {
        margin-left: 10px;
        font-weight: bold;
        float: left;
      }
      i {
        width: 2px;
        height: 16px;
        float: left;
        background: red;
        margin-top: 17px;
      }
      .input {
        display: inline-block;
        border: 1px solid #e1e1e1;
        line-height: 36px;
        background-color: #fff;
        margin: 0 20px;
        width: 200px;
        padding-left: 15px;
      }
      .el-input {
        /* width: 50%; */
        margin-left: 20px;
        .el-input__inner {
          height: 34px;
          width: 180%;
        }
      }
    }
    .right {
      padding: 0 10px;
      cursor: pointer;
      .el-icon-arrow-down {
        color: #999;
        font-size: 24px;
        line-height: 48px;
      }
      .transform {
        transform: rotate(270deg);
      }
    }
  }
  .mt {
    margin-top: 0px;
  }
}

/* 规则包信息 */
.content {
  display: flex;
  /* height: calc(100vh - 300px); */
  /* min-height: 450px; */
  height: 450px;
  margin: 20px 10px 0 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}
.left-tree {
  width: 300px;
  margin-right: 10px;
  border: 1px solid #e1e1e1;
  .tree-filter {
    padding: 20px 20px 0 20px;
  }
}
.right-main {
  flex: 1;
  overflow: auto;
  .btn-list {
    background: #f8f8f8;
    padding: 10px 0;
    margin-bottom: 10px;
  }
}
.handle-btn {
  cursor: pointer;
  color: #409eff;
  display: inline-block;
  padding: 0 8px;
}
/deep/ .el-tree {
  background: #fff !important;
  height: calc(100% - 100px);
  overflow: auto;
  margin-top: 20px;
  padding-top: 0px;
}
/deep/ .el-tree .el-tree-node__content .is-disabled {
  display: block !important;
}
</style>